<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />

    <!--组件 新闻标题  -->
    <hr />
    <div>
      <CreatedcssCreinput ref="creinput"></CreatedcssCreinput>
      <!-- 提交新闻 -->
      <div
        class="d-flex justify-content-center align-items-center column-gap-3"
        style="margin-bottom: 0.625rem"
      >
        <el-select
          v-model="classvalue.classvalue"
          placeholder="暂无分类"
          style="width: 140px"
          @change="changesort"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <CreatedcssCrebutton @click="addnewsitem"></CreatedcssCrebutton>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: "article",
});  
let   accessKeyId=import.meta.env.ALIBABA_CLOUD_ACCESS_KEY_ID
let  accessKeySecret= import.meta.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
console.log(accessKeyId,accessKeySecret);

let classvalue = ref({
  classvalue: "",
  classsort: 0,
});
let options: any = []; //分类数组
let creinput = ref();
async function addnewsitem() {
  let jiedian = creinput.value.$el;
  var inputElements = jiedian.getElementsByTagName("input");
  //这个才是正式的获取节点中的节点内容
  let inputElementsValue = inputElements[0].value;
  if (inputElementsValue == "") {
    alert("请输入新闻标题");
  } else if (valueHtml.value.length <= 11) {
    alert("新闻内容不能为空");
  } else {
    let result = await useFetch("/api/post/addnews", {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: {
        title: inputElementsValue,
        content: valueHtml.value,
        classify: {
          classvalue: classvalue.value.classvalue,
          classsort: classvalue.value.classsort,
        },
      },
    });
    if (result.data.value?.code == 2000) {
      alert("发布成功");
    }

    // if(result==2000){

    // }
  }
}
function changesort() {
  options.forEach((v: any) => {
    if (classvalue.value.classvalue == v.value) {
      classvalue.value.classsort = v.sort;
    }
  });
}
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
let mode: "default"; // 或 'simple'
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
let arr: any = [];
import $ from "jquery";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

// 编辑器实例，必须用 shallowRef--------------------------------------------------------------------
const editorRef = shallowRef();
// 内容 HTML
let valueHtml = ref("");
// 模拟 ajax 异步获取内容
onMounted(async () => {
  setTimeout(() => {
    valueHtml.value = "";
  }, 100);
  //从oss获取上传的图片
  let result = await $fetch("/api/post/getallimg", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
  });
  result.result.objects.forEach((v: any, i: any) => {
    if (i != 0) {
      arr.push(v.url);
    }
  });
  //从数据库获取4字标题
  let classify = await $fetch("/api/post/getclassify", {
    method: "POST",
  });
  classify.result.forEach((v: any) => {
    options.push({ value: v.title, label: v.title, sort: v.id });
  });
  options.unshift({ value: "", label: "暂无分类" }); ///在第一个位置添加空值
});

const toolbarConfig = {};
//上传图片发送地址
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    // 确保这里初始化了MENU_CONF为一个对象
    uploadImage: {
      async customUpload(file: any, insertFn: (arg0: string) => void) {
        // console.log(file, "file ");
        // console.log(file.name, "file ");
        const fileName = file.name;
        const reader = new FileReader();
        reader.onload = async (e) => {
          const base64 = e.target!.result;
          var base64img = base64.replace(/^data:image\/\w+;base64,/, "");
          let result = await $fetch("/api/post/upload", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: {
              name: fileName,
              filebuf: base64img, // 确保发送base64字符串
            },
          });
          console.log(result, " result ");
          insertFn(result.url);
        };
        reader.readAsDataURL(file);
      },
      // 其他上传图片的配置...
      // 单个文件上传成功之后
      onSuccess(file: File, res: any) {
        // TS 语法
        // onSuccess(file, res) {          // JS 语法
        arr.push(res.data.url);
      },
    },
  },
};

///////////////////////////////////////////////////////////////////////////////////

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

/////////////////自定义--------------------------------------------------------------------------
import {
  SlateNode,
  type IButtonMenu,
  type IDomEditor,
} from "@wangeditor/editor";

class MyButtonMenu implements IButtonMenu {
  showModal: boolean; // TS 语法
  modalWidth: number;
  // class MyButtonMenu {                       // JS 语法

  constructor() {
    this.title = "插入图片"; // 自定义菜单标题
    this.iconSvg = `<svg t="1713254419390" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1650" width="200" height="200"><path d="M891.306667 106.666667c26.154667 0 47.36 21.205333 47.36 47.36v342.101333h-76.8V183.466667H162.133333v430.293333l244.650667-170.154667 131.968 95.232v94.677334l-132.821333-95.829334L162.133333 707.370667V840.533333h376.618667v76.8H132.693333A47.36 47.36 0 0 1 85.333333 869.973333V154.026667c0-26.154667 21.205333-47.36 47.36-47.36h758.613334z m-71.509334 426.666666v153.557334l153.6 0.042666v76.8h-153.6v153.6h-76.8v-153.6h-153.6v-76.8l153.6-0.042666V533.333333h76.8zM716.373333 302.506667a51.2 51.2 0 1 1 0 102.4 51.2 51.2 0 0 1 0-102.4z" fill="#636A80" p-id="1651"></path></svg>`; // 可选
    this.tag = "button";
    this.showModal = true;
    this.modalWidth = 500;
  }
  title: string;
  iconSvg?: string | undefined;
  hotkey?: string | undefined;
  alwaysEnable?: boolean | undefined;
  tag: string;
  width?: number | undefined;

  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  async getValue(editor: IDomEditor): Promise<string | boolean> {
    // TS 语法
    // getValue(editor) {                              // JS 语法

    return "";
  }

  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(editor: IDomEditor): boolean {
    // TS 语法
    // isActive(editor) {                    // JS 语法
    return false;
  }

  // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
  isDisabled(editor: IDomEditor): boolean {
    // TS 语法
    // isDisabled(editor) {                     // JS 语法
    return false;
  }

  // 点击菜单时触发的函数          value: string | boolean
  exec(editor: IDomEditor, value: any) {
    // TS 语法
    // exec(editor, value) {                              // JS 语法
    if (this.isDisabled(editor)) return;
    editor.insertText(value); // value 即 this.value(editor) 的返回值
  }
  // 弹出框 modal 的定位：1. 返回某一个 SlateNode； 2. 返回 null （根据当前选区自动定位）
  getModalPositionNode(editor: IDomEditor): SlateNode | null {
    // TS 语法
    // getModalPositionNode(editor) {                             // JS 语法
    return null; // modal 依据选区定位
  }

  // 定义 modal 内部的 DOM Element
  getModalContentElem(editor: any): Promise<any> {
    // TS 语法
    // getModalContentElem(editor) {                        // JS 语法
    const $newElement = $('<div class="row justify-content-between"></div>');

    arr.forEach((v: any) => {
      const $img = $(
        `<img style="width:100px;height:100px;margin:5px" src="${v}"></img>`
      );
      $newElement.append($img);
      $img.on("click", () => {
        // editor.insertText('dshfkhdsfk')
        editor.focus();

        editor.dangerouslyInsertHtml(`<img src="${v}" />`);
        const content = editor.getHtml();
        // console.log(content, "输出编辑器中的所有内容"); // 输出编辑器中的所有内容
      });
    });

    return $newElement[0]; // 返回 DOM Element 类型

    // PS：也可以把 $content 缓存下来，这样不用每次重复创建、重复绑定事件，优化性能
  }
}

const menu1Conf = {
  key: "menu1", // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new MyButtonMenu(); // 把 `YourMenuClass` 替换为你菜单的 class
  },
};
import { Boot } from "@wangeditor/editor";
import type { DOMElement } from "@wangeditor/editor/dist/editor/src/utils/dom";

Boot.registerMenu(menu1Conf); //注册工具成功
toolbarConfig.insertKeys = {
  index: 32, // 插入的位置，基于当前的 toolbarKeys
  keys: ["menu1"],
};
</script>

<style scoped></style>
